import re

import cv2
import pytesseract

# 设置 Tesseract 可执行文件路径
pytesseract.pytesseract.tesseract_cmd = r'D:\dev\Tesseract-OCR\tesseract.exe'


def add_mosaic(img, x, y, w, h, mosaic_size=10):
    # 确保选择的区域在图像内
    if x < 0 or x + w > img.shape[1] or y < 0 or y + h > img.shape[0]:
        print("选择的区域超出图像边界，无法添加马赛克")
        return img

    sub_img = img[y:y + h, x:x + w]  # 身份证号区域

    if sub_img.size == 0:
        print("选择的区域为空，无法添加马赛克")
        return img

    sub_img_small = cv2.resize(sub_img, (mosaic_size, mosaic_size), interpolation=cv2.INTER_LINEAR)
    sub_img_mosaic = cv2.resize(sub_img_small, (w, h), interpolation=cv2.INTER_NEAREST)

    img[y:y + h, x:x + w] = sub_img_mosaic
    return img


# 读取图像
image_path = "./image/27.png"
img = cv2.imread(image_path)

custom_config = r'--oem 3 --psm 4 '
# 识别图像中的文字及其位置信息
data = pytesseract.image_to_data(img, lang=' eng+chi_sim', config=custom_config,
                                 output_type=pytesseract.Output.DICT)

print(data['text'])
# 合并识别的文本
full_text = ''.join(data['text'])

pattern = r'[0-9a-zA-Z]{18}'

# 使用正则表达式匹配18位的身份证号码
id_number_match = re.search(pattern, full_text)
if id_number_match:
    id_number = id_number_match.group(0)
    print("识别到身份证号:", id_number)

    # 确定身份证号的坐标位置
    for i in range(len(data['text'])):
        if data['text'][i] == id_number:  # 检查识别的文本中是否包含身份证号
            print(data['text'][i])
            x = data['left'][i]
            y = data['top'][i]
            w = data['width'][i]  # 根据身份证号的长度计算宽度
            h = data['height'][i]

            # 原图一半区域
            x = int(x + w / 2)
            w = int(w / 2)

            # 添加马赛克到整个身份证号
            if x >= 0 and y >= 0 and x + w <= img.shape[1] and y + h <= img.shape[0]:
                img = add_mosaic(img, x, y, w, h, mosaic_size=15)
            else:
                print("计算的区域超出图像边界，无法添加马赛克")
            break
else:
    print("未识别到有效的身份证号")
# 显示或保存处理后的图像
cv2.imshow("ID Card with Mosaic", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
